package com.base_java.common;

import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Component;
import org.springframework.web.servlet.HandlerExceptionResolver;
import org.springframework.web.servlet.ModelAndView;
import org.springframework.web.servlet.view.json.MappingJacksonJsonView;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

/**
 * @description: 处理全局异常
 * @author: mingtai
 * @createDate: 23:29 2021/4/28
 * @version: 1.0
 */

/**
 *  注解@Component 是组件的意思，加了这个注解，这个bean才能被spring容器管理，才能全局异常生效
 *
 *  全局异常 一定要交给spring管理，加上注解。才能生效。
 */
@Slf4j
@Component
public class ExceptionResolver implements HandlerExceptionResolver {
    @Override
    public ModelAndView resolveException(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse, Object o, Exception e) {
        log.error("{} Exception", httpServletRequest.getRequestURI(), e);
        // MappingJacksonJsonView 显示过时，是因为Jackson2.x以上使用MappingJackson2JsonView，本项目使用的1.9
        ModelAndView modelAndView = new ModelAndView(new MappingJacksonJsonView());
        modelAndView.addObject("status", ResponseCode.ERROR.getCode());
        modelAndView.addObject("msg", "程序异常,请联系技术人员");
        modelAndView.addObject("data", e.toString());
        log.info("全局异常拦截结束了...");
        return modelAndView;
    }
}



